package com.jumi.microservice.service.logistics.express;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jumi.microservice.dto.logistics.Logistics;
import com.jumi.microservice.dto.logistics.LogisticsSearchRequest;
import com.jumi.microservice.dto.logistics.LogisticsSearchResponse;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author by mazhao
 * @Classname ResponseController
 * @Description TODO
 * @Date 2020/11/19 14:18
 */
public class ResponseController {

    /**
     * 校验返回结果
     * @param jsonArray
     * @param request
     * @return
     */
    public LogisticsSearchResponse checkResult(JSONArray jsonArray, LogisticsSearchRequest request){
        LogisticsSearchResponse logisticsSearchResponse = new LogisticsSearchResponse();
        logisticsSearchResponse.setLogisticsName(request.getExpressName());
        logisticsSearchResponse.setLogisticsNo(request.getLogisticsNo());
        if(jsonArray==null || jsonArray.isEmpty()){
            logisticsSearchResponse.setList(new ArrayList<>());
        }
        return logisticsSearchResponse;
    }

    /**
     * 组装返回实体类
     * @param logisticsSearchResponse
     * @param jsonArr
     * @param descKey
     * @param dateKey
     * @return
     */
    public LogisticsSearchResponse controller(LogisticsSearchResponse logisticsSearchResponse,JSONArray jsonArr,
                                              String descKey,String dateKey) {
        if(jsonArr==null || jsonArr.isEmpty()){
            return logisticsSearchResponse;
        }
        List<Logistics> list = new ArrayList<>();
        for (Object j : jsonArr) {
            JSONObject json = JSONObject.parseObject(j.toString());
            Logistics logistics = new Logistics();
            if(json.getString(descKey)==null || json.getString(dateKey)==null){
                return logisticsSearchResponse;
            }
            logistics.setDesc(json.getString(descKey));
            logistics.setDate(json.getString(dateKey));
            list.add(logistics);
        }
        list = list.stream().sorted(Comparator.comparing(Logistics::getDate).reversed()).collect(Collectors.toList());
        logisticsSearchResponse.setList(list);
        return logisticsSearchResponse;
    }
}
